<template>
  <div>
    <!-- 查询区域 -->
    <el-card shadow="never" class="query-card">
      <el-form :model="queryParams" label-width="70px" :inline="true" ref="queryFormRef">
        <!-- 姓名 -->
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable />
        </el-form-item>

        <!-- 所属机构 -->
        <el-form-item label="所属机构" prop="relatedRemark">
          <el-input v-model="queryParams.relatedRemark" placeholder="请输入机构名称" clearable />
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="enabled">
          <el-select class="!w-50" v-model="queryParams.enabled" placeholder="全部" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <!-- 创建时间 -->
        <el-form-item label="创建时间" prop="createTimeRange">
          <el-date-picker format="YYYY/MM/DD" class="!w-70" v-model="queryParams.createTimeRange" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <!-- 审核时间 -->
        <el-form-item label="审核时间" prop="auditTimeRange">
          <el-date-picker format="YYYY/MM/DD" class="!w-70" v-model="queryParams.auditTimeRange" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <!-- 审核状态 -->
        <el-form-item label="审核状态" prop="audit">
          <el-select v-model="queryParams.audit" class="!w-50" placeholder="全部" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="审核通过" value="approved" />
            <el-option label="审核驳回" value="rejected" />
          </el-select>
        </el-form-item>

        <!-- 查询和重置按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>



    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <div>
        <!-- Add New Button -->
        <el-button type="primary" style="margin-bottom: 16px;" @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%" header-cell-class-name="table-header">
        <!-- 编号 -->
        <el-table-column prop="userId" label="编号" width="180" align="center" />

        <!-- 手机号码 -->
        <el-table-column prop="phonenumber" label="手机号码" width="120" align="center" />

        <!-- 所属角色 -->
        <el-table-column prop="roleName" label="所属角色" width="100" align="center" />

        <!-- 姓名 -->
        <el-table-column prop="nickName" label="姓名" align="center" />

        <!-- 性别 -->
        <el-table-column prop="sex" label="性别" width="60" align="center"
          :formatter="row => transformDict('gender', row.sex)" />

        <!-- 审核状态 -->
        <el-table-column prop="audit" label="审核状态" width="100" align="center"
          :formatter="row => transformDict('auditStatus', row.audit)" />

        <!-- 所属机构 -->
        <el-table-column prop="relatedRemark" label="所属机构" width="100" align="center" />

        <!-- 状态 -->
        <el-table-column prop="enabled" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.enabled == 1 ? 'success' : 'info'">
              {{ row.enabled == 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间" width="100" align="center" />

        <!-- 审核时间 -->
        <el-table-column prop="auditTime" label="审核时间" width="100" align="center" />

        <!-- 操作 -->
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="success" @click="handleView(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页（可选） -->
      <div class="pagination" style="margin-top: 20px; text-align: right">
        <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :total="total" layout="total, prev, pager, next" @current-change="getData" />
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" title="人员信息" width="800px">
      <el-form :disabled="option === 'view'" :model="form" :rules="rules" label-width="100px" ref="formRef"
        size="default">
        <!-- 真实姓名 -->
        <el-form-item label="真实姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入真实姓名" />
        </el-form-item>

        <!-- 手机号码 -->
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 所属机构 -->
        <el-form-item label="所属机构" prop="relatedRemark">
          <!-- <el-input v-model="form.relatedRemark" placeholder="请输入所属机构" /> -->
          <el-autocomplete v-model="form.relatedRemark" class="w-full" value-key="orgName" @select="handleSelectOrg"
            :fetch-suggestions="querySearch" clearable placeholder="请输入机构名称" />
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item v-if="option === 'add'" label="新密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入新密码" />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item v-if="option === 'add'" label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请确认新密码" />
        </el-form-item>

        <!-- 上传头像 -->
        <el-form-item label="上传头像" prop="avatar">
          <OneUpload v-model="form.avatar"></OneUpload>
        </el-form-item>

        <!-- 上传工牌 -->
        <el-form-item label="上传工牌" prop="badgeUrl">
          <OneUpload v-model="form.badgeUrl"></OneUpload>
        </el-form-item>

        <!-- 所属角色 -->
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId" />
            <!-- 可根据实际业务添加更多角色 -->
          </el-select>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="enabled">
          <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>

        <!-- 工作状态 -->
        <el-form-item label="工作状态" prop="workStatus">
          <el-radio-group v-model="form.workStatus">
            <el-radio :label="1">工作中</el-radio>
            <el-radio :label="0">休息中</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" v-if="option != 'view'" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getOrganizationMemberList } from '@/api/organization'
import OneUpload from '@/components/oneUpload.vue';
import { getRoleList } from '@/api/common';

import { useDict, transformDict } from '@/hooks/dict';

// 表单方法
const dialogVisible = ref(false)

useDict('auditStatus', 'gender')

// Form data
const form = reactive({
  userId: '',
  phonenumber: '',
  roleName: '',
  nickName: '',
  sex: '',
  audit: '',
  badgeUrl: '',
  relatedRemark: '',
  avatar: '',
  workStatus: '',
  enabled: '',
  createTime: '',
  auditTime: ''

})


// Function to reset form data
const reset = () => {
  form.userId = ''
  form.phonenumber = ''
  form.roleName = ''
  form.nickName = ''
  form.sex = ''
  form.audit = ''
  form.relatedRemark = ''
  form.avatar = ''
  form.badgeUrl = ''
  form.workStatus = ''
  form.enabled = ''
  form.createTime = ''
  form.auditTime = ''
}

const rules = reactive({
  nickName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phonenumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  roleName: [{ required: true, message: '请输入所属单位', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为 6 到 20 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请设置状态', trigger: 'change' }],
  workStatus: [{ required: true, message: '请选择工作状态', trigger: 'change' }]
});

// Function to open dialog and fill form data
const openDialog = (row = {}) => {
  Object.assign(form, row)
  dialogVisible.value = true
}

const formRef = ref(null)

import { cloneDeep } from 'lodash-es'

// Function to submit form
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = cloneDeep(form)
      formData.roleIds = [formData.roleId]
      // 表单验证通过，提交数据
      // 这里可以调用 API 提交数据
      if (formData.userId) {
        updateInstitutionUser(formData).then(res => {
          if (res.code == 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            getData()
          }
        })
      } else {
        addInstitutionUser(formData).then(res => {
          if (res.code == 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getData()
          }
        })
      }
    } else {
      ElMessage.error('请填写正确的信息')
    }
  })
  // dialogVisible.value = false
}

const handleAdd = () => {
  reset()
  option.value = "add"
  dialogVisible.value = true
}

const handleSelectOrg = (item) => {
  form.relatedId = item.id
}

import { addInstitutionUser, manageOrganizations, updateInstitutionUser } from '@/api/institution'
const querySearch = (queryString, cb) => {
  if (queryString.length <= 3) {

    return cb([])
  }
  manageOrganizations({ orgName: queryString }).then(res => {
    if (res.code == 200) {
      cb(res.rows)
    }
  })
}

const option = ref("")

// Modify handleEdit and handleView to open dialog
const handleEdit = (row) => {
  openDialog(row)
  option.value = "edit"
}

const handleView = (row) => {
  openDialog(row)
  option.value = "view"
}

// 查询参数
const queryParams = reactive({
  nickName: '',
  relatedRemark: '',
  status: '',
  createTimeRange: [],
  auditTimeRange: [],
  pageNum: 1,
  pageSize: 10,
  auditStatus: ''
})

const total = ref(0)
const roleList = ref([])
// 初始化
onMounted(() => {
  getData()

  getRoleList({ roleType: "1" }).then(res => {
    if (res.code == 200) {
      roleList.value = res.rows
    }
  })
})

// 表单引用
const queryFormRef = ref(null)


const getData = () => {
  getOrganizationMemberList(queryParams).then(res => {
    tableData.value = res.rows
    total.value = res.total
  })
}

// 表格数据
const tableData = ref([])



// 查询处理
const handleQuery = () => {
  console.log('查询条件:', { ...queryParams })
  getData()
  // 调用 API 获取数据
}

// 重置处理
const handleReset = () => {
  queryFormRef.value?.resetFields()
  queryParams.createTimeRange = []
  queryParams.auditTimeRange = []
  // 可触发重新查询
  handleQuery()
}



// 临时引入 ElMessage（实际项目中从 Element Plus 引入）
import { ElMessage } from 'element-plus'
</script>

<style scoped lang="scss">
:deep(.table-header .cell) {
  white-space: nowrap;
  width: auto;
}

.query-card {
  margin-bottom: 16px;
  border: none;
}

.table-card {
  border: none;
}

.table-header {
  background-color: #f8f8f8 !important;
  height: 60px;
  font-weight: bold;
}
</style>
